<template>
    <el-card v-loading="loading.data">
        <div slot="header">
            <template v-if="isEdit">
                编辑
                <el-button type="text" @click="$router.push('/anchor/'+anchor.id)">{{anchor.name}}</el-button>
            </template>
            <template v-else>
                创建主播
            </template>
        </div>
        <el-form class="detail-anchor-info" :rules="rules" :model="anchor" label-width="150px" ref="anchorForm">
            <el-form-item label="主播名称" prop="name">
                <el-input v-model="anchor.name" class="width200"/>
            </el-form-item>
            <el-form-item label="主播性别" prop="gender" :rules="[{required:true}]">
                <el-radio-group v-model="anchor.gender">
                    <el-radio :label="true">男</el-radio>
                    <el-radio :label="false">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="所在平台" prop="platform_id">
                <el-select v-model="anchor.platform_id">
                    <el-option
                            v-for="p in platforms"
                            :key="p.id"
                            :label="p.name"
                            :value="p.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="主播级别" prop="level_id">
                <el-select v-model="anchor.level_id">
                    <el-option
                            v-for="l in levels"
                            :key="l.id"
                            :label="l.name"
                            :value="l.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="小葫芦ID" prop="_id">
                <el-input v-model="anchor._id" placeholder="ID，不是网址" clearable class="width200"/>
            </el-form-item>
            <el-form-item label="直播间网址" prop="url">
                <el-input v-model="anchor.url" placeholder="请填写网址，带http://" clearable style="width: 350px;">
                    <a :href="anchor.url" target="_blank" slot="append" style="color: #409eff;">打开连接</a>
                </el-input>
            </el-form-item>
            <el-form-item label="经纪人" v-if="$store.state.user.level.id <= 2">
                <project_search_user placeholder="搜索 用户" v-model="anchor.agent" @change="selectAgent"
                                     @clear="selectAgent(null)"/>
            </el-form-item>
            <el-form-item label="分类" prop="categories">
                <anchor_search_category v-model="anchor.option.categories"/>
                <br>
                可以选择已有的分类 或 自行创造分类名称，但是不会影响到项目使用的分类数据。
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="submit" v-if="anchor.id > 0" :loading="loading.submit">保存</el-button>
                <el-button type="success" @click="submit" v-else :loading="loading.submit">创建</el-button>
            </el-form-item>
            <el-form-item>
                <my-alert ref="alert"/>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script>
    import MyAlert from "../component/my_alert";
    import Anchor_search_category from "../component/anchor_search_category";
    import Project_search_user from "../component/project_search_user";

    export default {
        name: 'categories_aggregation',
        components: {
            Project_search_user,
            Anchor_search_category,
            MyAlert
        },
        data() {
            const notEmpty = [{required: true, message: '请输入内容', trigger: 'blur'}];
            const url = [{
                required: true, trigger: 'blur',
                type: 'url', message: '请填写完整的网址，开头需要有http://或https://',
            }];
            const selection = message => [{
                required: true,
                validator: (rule, value, callback) => {
                    if (value > 0)
                        return callback();
                    callback(new Error(message));
                }, trigger: 'blur'
            }];
            return {
                loading: {data: true, submit: false,},
                platforms: [],
                levels: [],
                anchor: {
                    id: '',
                    _id: '',
                    name: '',
                    url: '',
                    gender: true,
                    platform_id: '',
                    level_id: '',
                    option: {categories: []}
                },
                rules: {
                    name: notEmpty,
                    _id: [{required: false}],
                    url,
                    platform_id: selection('请选择平台'),
                    level_id: selection('请选择主播级别'),
                    categories: [{
                        validator: (rule, value, callback) => {
                            for (let i = 0; i < this.anchor.option.categories.length; i++) {
                                let item = this.anchor.option.categories[i].trim();
                                if (_.isEmpty(item))
                                    return callback('存在只有空格的分类名称，需要填写名称');
                                this.anchor.option.categories[i] = item;
                            }
                            callback();
                        },
                    }],
                },
            };
        },
        methods: {
            fetch() {
                let all = [
                    this.$http.get('/api/platform'),
                    this.$http.get('/api/xiaohulu/level')
                ];
                console.log({isEdit: this.isEdit});
                if (this.isEdit)
                    all.push(this.$http.get('/api/xiaohulu/anchor/' + this.$route.params.id));

                Promise.all(all).then(res => {
                    this.platforms = res[0].data;
                    this.levels = res[1].data;
                    if (this.isEdit) {
                        if (res[2])
                            this.anchor = res[2].data;
                        else
                            this.$router.replace('/404');
                    }
                    this.loading.data = false;
                    console.log('loading.data', this.loading.data);
                });
            },
            submit() {
                this.$refs['anchorForm'].validate(valid => {
                    if (!valid)
                        return;
                    this.loading.submit = true;
                    this.$refs.alert.hide();
                    this.$http.post('/api/xiaohulu/anchor/', this.anchor).then(res => {
                        if (this.anchor.id > 0) {
                            this.loading.submit = false;
                            this.$refs.alert.success('保存成功', 1500);
                        }
                        else {
                            this.$router.push('/anchor/' + res.data.id);
                        }
                    }).catch(err => {
                        this.loading.submit = false;
                        this.$refs.alert.error(err.response.data);
                    });
                });
            },
            selectAgent(userId) {
                this.anchor.agent_id = userId;
            }
        },
        computed: {
            isEdit() {
                return this.$route.params.id > 0;
            }
        },
        mounted() {
            this.fetch();
        },
    }
</script>

<style scoped>
    .width200 {
        width: 200px;
    }
</style>